package com.zcs.java.demo.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class POIUtils {
    // 外部导入的Excel文件放到这个目录里面
    private static final String DIR_IMPORT = System.getProperty("user.dir") + "/src/main/resources/import";
    // Java导出的Excel文件会保存到这个目录里面
    private static final String DIR_EXPORT = System.getProperty("user.dir") + "/src/main/resources/export";

    public static Workbook createWorkbook(String excelName) throws IOException, InvalidFormatException {
        File excelFile = new File(DIR_IMPORT, excelName);
        return createWorkbook(excelFile);
    }

    public static Workbook createWorkbook(File excelFile) throws IOException, InvalidFormatException {
        if (excelFile.isFile() && excelFile.exists()) {
            String[] split = excelFile.getName().split("\\.");  //.是特殊字符，需要转义！！！！！
            // 根据文件后缀（xls/xlsx）进行判断
            if ("xls".equals(split[1])) {
                FileInputStream fis = new FileInputStream(excelFile);   //文件流对象
                return new HSSFWorkbook(fis);
            } else if ("xlsx".equals(split[1])) {
                return new XSSFWorkbook(excelFile);
            } else {
                System.out.println("文件类型错误!-->" + split[1]);
            }
        } else {
            System.out.println("找不到指定文件，请确保文件存在。");
        }
        return null;
    }
}
